package com.gqzm.side.common.interceptor;

import com.gqzm.side.common.result.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: {@link LoginInterceptor}
 * @description: 登录拦截，并填充用户信息
 * @author: peter qin
 * @date: 2023 07 14
 * @version: 1.0
 **/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 用户登录拦截及token校验
     *
     * @param request 请求
     * @param response 响应
     * @param handler 处理
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        String userCode = request.getHeader("User-Code");
        String userName = request.getHeader("User-Name");
        UserUtils.setUser(
                UserUtils.User.builder()
                .userCode(userCode)
                .userName(userName)
                .build());
        return true;
    }


    /**
     * 请求完成处理
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex) throws Exception {
        UserUtils.removeUser();
    }
}
